<template>
  <div class="chat-window" :class="{ 'collapsed': collapsed }">
    <div class="chat-header">
      <div class="friend-info">
        <div>
          <h3>{{ friend.name }}</h3>
          <p class="status" :class="{
            'online': friend.online && friend.status === 1,
            'offline': !friend.online && friend.status === 1,
            'pending': friend.status === 0,
            'refuse': friend.status === 2,
            'blocked': friend.status === 3
          }">
            <template v-if="friend.status === 0">待确认好友</template>
            <template v-else-if="friend.status === 2">已拒绝</template>
            <template v-else-if="friend.status === 3">已拉黑</template>
            <template v-else>{{ friend.online ? '在线' : `离线 ${friend.lastSeen}` }}</template>
          </p>
        </div>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <template v-if="friend.status === 1">
        <div
            v-for="(message, index) in messages"
            :key="index"
            class="message"
            :class="{ 'sent': message.isSelf, 'received': !message.isSelf }"
        >
          <div class="message-content">{{ message.content }}</div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          <div v-if="message.status" class="message-status">
            {{ message.status }}
          </div>
        </div>
      </template>
      <div v-else class="status-message">
        <template v-if="friend.status === 0">
          <p>等待对方确认好友请求</p>
        </template>
        <template v-else-if="friend.status === 2">
          <p v-if="isRejectedByMe">你已拒绝对方的好友请求</p>
          <p v-else>对方已拒绝你的好友请求</p>
        </template>
        <template v-else>
          <p>好友关系异常</p>
        </template>
      </div>
    </div>

    <div class="chat-input-cw" v-if="friend.status === 1">
      <textarea
          v-model="newMessage"
          @keydown.enter.prevent="sendMessage"
          :placeholder="friend.online ? '输入消息...' : '好友离线，消息将在对方上线后送达'"
          rows="1"
          ref="messageInput"
      ></textarea>
      <button @click="sendMessage" :disabled="!newMessage.trim()">
        {{'发送'}}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useChatSimpleStore } from '@/stores/chatSimpleStore.js'
import { useAuthStore } from '@/stores/modules/authStore.js'

const props = defineProps({
  friend: {
    type: Object,
    required: true,
    default: () => ({
      id: null,
      name: '未知好友',
      avatar: 'https://randomuser.me/api/portraits/lego/1.jpg',
      online: false,
      status: 1,
      lastSeen: '未知',
      receiverId: null // 确保包含receiverId
    })
  },
  collapsed: Boolean
})

const chatStore = useChatSimpleStore()
const authStore = useAuthStore()
const newMessage = ref('')
const messagesContainer = ref(null)
const messageInput = ref(null)

// 计算属性：判断是否是我拒绝的
const isRejectedByMe = computed(() => {
  return props.friend.receiverId === authStore.userInfo.id
})

console.log('[ChatWindow] 初始化组件，当前好友:', props.friend)

// 获取与当前好友的聊天记录
const messages = computed(() => {
  if (!props.friend || props.friend.status !== 1) {
    console.log('[messages computed] 好友状态异常或未选择好友，返回空数组')
    return []
  }

  // 从store获取私聊消息
  const privateMessages = chatStore.getPrivateMessages(props.friend.id)
  console.log('[messages computed] 从store获取的原始消息:', privateMessages)

  // 如果没有消息，显示默认欢迎消息
  if (privateMessages.length === 0) {
    const welcomeMessage = {
      content: props.friend.online
          ? `我们已成为好友，开始聊天吧！`
          : `${props.friend.name}当前不在线，留言后对方上线会看到`,
      timestamp: new Date(),
      isSelf: false
    }
    console.log('[messages computed] 无历史消息，返回欢迎消息:', welcomeMessage)
    return [welcomeMessage]
  }

  // 格式化消息数据，确保包含必要字段
  const formattedMessages = privateMessages.map(msg => ({
    content: msg.content,
    timestamp: msg.timestamp,
    isSelf: msg.isSelf,
    status: msg.status
  }))

  console.log('[messages computed] 格式化后的消息列表:', formattedMessages)
  return formattedMessages
})

// 格式化时间显示
const formatTime = (date) => {
  if (!(date instanceof Date)) {
    date = new Date(date)
  }
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      console.log('[scrollToBottom] 滚动消息容器到底部')
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim() || !props.friend || props.friend.status !== 1) {
    console.log('[sendMessage] 发送消息条件不满足，取消发送')
    return
  }

  console.log('[sendMessage] 准备发送消息:', newMessage.value, '给好友:', props.friend.id)

  // 使用store的sendToUser方法发送私聊消息
  chatStore.sendToUser(newMessage.value, props.friend.id)

  newMessage.value = ''
  scrollToBottom()
}

// 当好友切换时，清除未读消息计数
watch(() => props.friend, (newFriend) => {
  console.log('[friend watcher] 好友变更:', newFriend)
  if (newFriend && newFriend.status === 1) {
    console.log('[friend watcher] 清除未读计数，好友ID:', newFriend.id)
    chatStore.clearUnreadCount(newFriend.id)
    nextTick(() => {
      scrollToBottom()
      if (messageInput.value) {
        console.log('[friend watcher] 聚焦到输入框')
        messageInput.value.focus()
      }
    })
  }
}, { immediate: true })

// 监听消息变化
watch(() => chatStore.privateMessages, (newMessages) => {
  console.log('[privateMessages watcher] 私聊消息变化:', newMessages)
  if (props.friend?.id && newMessages[props.friend.id]) {
    console.log('[privateMessages watcher] 当前好友消息更新:', newMessages[props.friend.id])
    scrollToBottom()
  }
}, { deep: true })

// 监听好友在线状态变化
watch(() => chatStore.friendList, (newFriendList) => {
  const currentFriend = newFriendList.find(f => f.id === props.friend?.id)
  if (currentFriend) {
    console.log('[friendList watcher] 当前好友状态更新:', currentFriend)
    // 如果好友上线，滚动到底部显示最新消息
    if (currentFriend.online) {
      scrollToBottom()
    }
  }
}, { deep: true })

onMounted(() => {
  console.log('[onMounted] 组件挂载完成')

  if (messageInput.value && props.friend?.status === 1) {
    console.log('[onMounted] 聚焦到输入框')
    messageInput.value.focus()
  }

  // 连接WebSocket（如果尚未连接）
  if (chatStore.connectionStatus === 'disconnected') {
    console.log('[onMounted] 检测到未连接，开始连接WebSocket')
    chatStore.connect()
  } else {
    console.log('[onMounted] WebSocket连接状态:', chatStore.connectionStatus)
  }

  // 清除当前好友的未读消息计数
  if (props.friend?.status === 1) {
    console.log('[onMounted] 清除未读计数，好友ID:', props.friend.id)
    chatStore.clearUnreadCount(props.friend.id)
  }

  // 初始滚动到底部
  scrollToBottom()
})
</script>

<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
  transition: all 0.3s ease;
}

.chat-header {
  padding: 5px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.friend-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.status {
  font-size: 0.9em;
}

.status.online {
  color: #2ecc71;
}

.status.offline {
  color: #95a5a6;
}

.status.pending {
  color: #f39c12;
}

.status.refuse {
  color: #e74c3c;
}

.status.blocked {
  color: #e74c3c;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 15px;
  max-width: 80%;
  width: fit-content;
}

.message.sent {
  align-self: flex-end;
}

.message.received {
  align-self: flex-start;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  display: inline-block;
}

.message.sent .message-content {
  background-color: #007bff;
  color: white;
}

.message.received .message-content {
  background-color: #e9ecef;
  color: #333;
}

.message-time {
  font-size: 0.75rem;
  color: #666;
  margin-top: 5px;
}

.message-status {
  font-size: 0.7rem;
  color: #999;
  margin-top: 2px;
  text-align: right;
}

.offline-hint {
  color: #f39c12;
  margin-left: 5px;
}

.chat-input-cw {
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  width: 975px;
}

.chat-input-cw textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
  resize: none;
  max-height: 120px;
}

.chat-input-cw button {
  margin-left: 10px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 20px;
}

.chat-input-cw button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.status-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #666;
  text-align: center;
}

@media (max-width: 768px) {
  .chat-window.collapsed {
    margin-top: 0;
  }

  .message {
    max-width: 90%;
  }

  .chat-input-cw {
    width: 100%;
  }
}
</style>